package com.medicinezp.baseconfig.controller;

import cn.hutool.crypto.SecureUtil;
import com.medicinezp.baseconfig.config.TencentMapConfig;
import com.medicinezp.common.core.domain.AjaxResult;
import com.medicinezp.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @author lun.zhang
 * @create 2022/7/19 10:34
 */
@RequestMapping("/util")
@RestController
public class UtilController {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private TencentMapConfig tencentMapConfig;
    @Bean
    public RestTemplate restTemplate(){
        // RestTemplate restTemplate = new RestTemplate();
        //设置中文乱码问题方式一
        // restTemplate.getMessageConverters().add(1,new StringHttpMessageConverter(Charset.forName("UTF-8")));
        // 设置中文乱码问题方式二
        // restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8)); // 支持中文编码
        return new RestTemplate();
    }
    /**
     * lat<纬度>,lng<经度>
     *
     * @param lat
     * @param lng
     * @return
     */
    @GetMapping("/parseLocation")
    public AjaxResult parseLocation(String lat, String lng ) {
        if (StringUtils.isEmpty(lat) || StringUtils.isEmpty(lng)  ) {
            return AjaxResult.error("not.null");
        }
        String latLng = lat+","+lng;
        String str ="/ws/geocoder/v1?get_poi=1&key=" + tencentMapConfig.getTencentMapKey() + "&location=" + latLng + tencentMapConfig.getTencentMapSK();
        String param ="/ws/geocoder/v1?get_poi=1&key=" + tencentMapConfig.getTencentMapKey() + "&location=" + latLng;

        String sign =  SecureUtil.md5(str);
        String url = "https://apis.map.qq.com"+param+"&sig="+sign;
        ResponseEntity<Map> forEntity = restTemplate.getForEntity(url, Map.class);
        Map body = forEntity.getBody();
        return AjaxResult.success(body.get("result"));
    }
}
